package ntd.util.modular.other.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.Data;
import ntd.util.cache.FactoryCache;
import ntd.util.config.common.bo.ResponseBO;
import ntd.util.config.common.exception.ComException;
import ntd.util.frame.auth.ToolLogin;
import ntd.util.modular.account.entity.Account;
import ntd.util.modular.account.service.AccountService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;
import java.util.Map;

@RestController
@RequestMapping("/auth")
public class ControllerAuth {

    @Resource
    private AccountService accountService;

    @PostMapping("/login")
    public ResponseBO login(@Validated @RequestBody LoginInBO loginInBO) {
        if (StrUtil.isNotBlank(loginInBO.getUuid())){
            String code = FactoryCache.cache(loginInBO.uuid).cache();
            if (!loginInBO.getCode().equals(code)) {
                throw new ComException("请输入正确的验证码！");
            }
        }
        Account one = accountService.query()
                .eq("account", loginInBO.getUsername())
                .eq("password", loginInBO.getPassword())
                .one();
        if (ObjectUtil.isNull(one)) {
            return ResponseBO.err("账户登录失败，请检查后重试！");
        }
        return new ResponseBO<>(ToolLogin.createToken(one.getId()));
    }

    @PostMapping("/register")
    public ResponseBO register(@Validated @RequestBody LoginInBO loginInBO) {
        if (StrUtil.isNotBlank(loginInBO.getUuid())){
            String code = FactoryCache.cache(loginInBO.uuid).cache();
            if (!loginInBO.getCode().equals(code)) {
                throw new ComException("请输入正确的验证码！");
            }
        }
        Account account = new Account();
        account.setAccount(loginInBO.getUsername());
        account.setPassword(loginInBO.getPassword());
        account.setFlagAdmin(false);
        if (!accountService.saveOrUpdate(account)) {
            return ResponseBO.err("注册失败，请检查后重试！");
        }
        return new ResponseBO<>(account.getAccount());
    }

    /**
     * 临时用户
     * @param loginInBO
     * @return
     */
    @PostMapping("/fm-temp")
    public ResponseBO<String> fmTemp(@RequestBody LoginInBO loginInBO) {
        JSONObject jsonObject = JSONUtil.parseObj(loginInBO.getData());
        String token = ToolLogin.createToken(IdUtil.simpleUUID());
        ToolLogin.setToken(token);
        for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
            ToolLogin.setData(entry.getKey(), entry.getValue());
        }
        return new ResponseBO<>(token);
    }

    /**
     * 用户数据
     * @return
     */
    @PostMapping("/data")
    public ResponseBO<Object> tempData(@RequestBody LoginInBO loginInBO) {
        // 检查用户登录状态
        ToolLogin.checkLogin();
        JSONObject jsonObject = JSONUtil.parseObj(loginInBO.getData());
        for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
            ToolLogin.setData(entry.getKey(), entry.getValue());
        }
        return new ResponseBO<>(ToolLogin.data());
    }

    @GetMapping("userinfo")
    public ResponseBO<Account> userinfo() {
        Account account = accountService.getById(ToolLogin.getCurrUserId());
        return new ResponseBO<>(account);
    }

    @Data
    public static class LoginInBO {
        @NotBlank
        private String username;
        @NotBlank
        private String password;
        private String uuid;
        private String code;

        private Object Data = new Object();

    }
}
